import sys
import traceback
import mysql.connector
from mysql.connector import Error
from PyQt5.QtWidgets import (
    QApplication, QDialog, QVBoxLayout, QLabel, QPushButton, QSplashScreen, QMessageBox
)
from PyQt5.QtGui import QIcon, QFont, QPixmap, QColor
from PyQt5.QtCore import Qt, QTimer

# 导入功能模块
from mainUI.Manager_main import AdminLogin, AdminDashboard
from mainUI.Customer_main import CustomerLoginDialog, CustomerDashboard

class DBUtils:
    """数据库工具类 - 完整修复版"""

    def __init__(self):
        self.connection = None
        self._connect()  # 初始化时立即尝试连接

    def _connect(self):
        """建立数据库连接 - 修复版"""
        try:
            # 总是尝试创建新连接
            self.connection = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234',
                autocommit=True,
                connect_timeout=5  # 添加连接超时
            )

            if self.connection.is_connected():
                print(f"成功连接到MySQL服务器 (版本 {self.connection.server_version})")
                return True
            return False

        except Error as e:
            print(f"数据库连接失败: {e}")
            traceback.print_exc()
            raise ConnectionError(f"无法连接数据库: {str(e)}")

    def is_connected(self):
        """检查连接状态"""
        try:
            return self.connection and self.connection.is_connected()
        except:
            return False

    def execute_query(self, query, params=None, fetch=True):
        """执行SQL查询 - 修复版"""
        cursor = None
        try:
            # 确保连接有效
            if not self.is_connected():
                print("连接已断开，尝试重新连接...")
                if not self._connect():
                    print("无法重新连接到数据库")
                    return None

            cursor = self.connection.cursor(dictionary=True)
            cursor.execute(query, params or ())

            if fetch:
                result = cursor.fetchall()
                return result if result else []
            else:
                self.connection.commit()
                return True

        except Error as e:
            print(f"查询执行失败: {e}")
            traceback.print_exc()
            if self.connection:
                self.connection.rollback()
            return None
        finally:
            if cursor:
                cursor.close()

    def disconnect(self):
        """安全关闭连接"""
        if self.is_connected():
            try:
                self.connection.close()
                print("数据库连接已关闭")
            except Error as e:
                print(f"关闭连接时出错: {e}")
        self.connection = None

def show_splash_screen(app):
    """显示启动画面"""
    splash_pix = QPixmap(800, 600)
    splash_pix.fill(QColor(30, 87, 153))  # 蓝色背景

    splash = QSplashScreen(splash_pix)
    splash.show()

    # 显示启动消息
    splash.showMessage("正在启动银行系统...", Qt.AlignBottom | Qt.AlignCenter, Qt.white)
    app.processEvents()

    # 模拟初始化过程
    QTimer.singleShot(3000, splash.close)  # 3秒后关闭
    return splash


class WelcomeScreen(QDialog):
    """欢迎屏幕和角色选择界面"""

    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.customer_window = None  # 添加客户窗口引用
        self.admin_window = None  # 添加管理员窗口引用

    def setup_ui(self):
        """初始化界面布局"""
        self.setWindowTitle("银行系统")
        self.setFixedSize(800, 600)

        layout = QVBoxLayout()
        layout.setContentsMargins(50, 50, 50, 50)
        layout.setSpacing(40)

        # 标题
        title = QLabel("欢迎使用银行管理系统")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 36px; font-weight: bold; color: white;")

        # 副标题
        subtitle = QLabel("请选择您的角色进入系统")
        subtitle.setAlignment(Qt.AlignCenter)
        subtitle.setStyleSheet("font-size: 20px; color: white;")

        # 按钮区域
        btn_layout = QVBoxLayout()
        btn_layout.setSpacing(20)

        # 客户按钮
        customer_btn = QPushButton("客户登录")
        customer_btn.setIcon(QIcon(":/icons/customer.png"))
        customer_btn.setStyleSheet(self.get_button_style("#2ecc71"))
        customer_btn.clicked.connect(self.open_customer_login)

        # 管理员按钮
        admin_btn = QPushButton("管理员登录")
        admin_btn.setIcon(QIcon(":/icons/admin.png"))
        admin_btn.setStyleSheet(self.get_button_style("#3498db"))
        admin_btn.clicked.connect(self.open_admin_login)

        # 退出按钮
        exit_btn = QPushButton("退出系统")
        exit_btn.setIcon(QIcon(":/icons/exit.png"))
        exit_btn.setStyleSheet(self.get_button_style("#e74c3c", "#c0392b"))
        exit_btn.clicked.connect(self.exit_system)

        btn_layout.addWidget(customer_btn)
        btn_layout.addWidget(admin_btn)
        btn_layout.addWidget(exit_btn)

        layout.addWidget(title)
        layout.addWidget(subtitle)
        layout.addLayout(btn_layout)

        # 版权信息
        footer = QLabel("© 2023 银行管理系统 v1.0.0")
        footer.setAlignment(Qt.AlignCenter)
        footer.setStyleSheet("color: rgba(255, 255, 255, 150); font-size: 14px;")
        layout.addWidget(footer)

        # 设置背景样式
        self.setStyleSheet("""
            QDialog {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e5799, stop:1 #2989d8);
            }
        """)

        self.setLayout(layout)

    def get_button_style(self, bg_color, hover_color=None):
        """生成按钮样式表"""
        if hover_color is None:
            hover_color = bg_color
        return f"""
            QPushButton {{
                background-color: {bg_color};
                color: white;
                font-size: 16px;
                font-weight: bold;
                padding: 20px;
                border-radius: 10px;
                min-width: 200px;
                border: none;
            }}
            QPushButton:hover {{
                background-color: {hover_color};
            }}
        """

    def open_customer_login(self):
        """打开客户登录界面（修复版）"""
        try:
            login = CustomerLoginDialog()
            if login.exec_() == QDialog.Accepted and hasattr(login, 'card_info') and login.card_info:
                self.hide()
                # 创建客户主界面实例并保持引用
                self.customer_window = CustomerDashboard(login.card_info, self)  # 添加self作为参数
                # 将客户主窗口的关闭信号连接到欢迎界面重显示方法
                self.customer_window.destroyed.connect(self.show_welcome)
                self.customer_window.show()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开客户界面: {str(e)}")
            self.show()

    def open_admin_login(self):
        """打开管理员登录界面（修复版）"""
        try:
            login = AdminLogin()
            if login.exec_() == QDialog.Accepted:
                self.hide()
                # 创建管理员主界面实例并传递自身引用
                self.admin_window = AdminDashboard(self)  # 传递 self
                # 将管理员主窗口的关闭信号连接到欢迎界面重显示方法
                self.admin_window.destroyed.connect(self.show_welcome)
                self.admin_window.show()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开管理界面: {str(e)}")
            self.show()

    def show_welcome(self):
        """显示欢迎界面，并重置窗口引用"""
        self.show()
        # 重置窗口引用
        if self.sender() == self.customer_window:
            self.customer_window = None
        elif self.sender() == self.admin_window:
            self.admin_window = None

    def exit_system(self):
        """退出系统"""
        self.reject()


def show_admin_dashboard():
    """显示管理员仪表板"""
    admin_panel = AdminDashboard()
    admin_panel.show


def show_customer_dashboard(card_info):
    """显示客户仪表板"""
    customer_dashboard = CustomerDashboard(card_info)
    customer_dashboard.show()


def main():
    # 设置全局异常处理
    def global_exception_hook(exctype, value, traceback_obj):
        """处理未捕获的异常"""
        error_msg = f"未捕获的异常: {exctype.__name__}, {str(value)}"
        print(error_msg)
        traceback.print_tb(traceback_obj)

        # 创建临时QApplication显示错误
        temp_app = QApplication(sys.argv)
        QMessageBox.critical(None, "系统错误", error_msg)
        sys.exit(1)

    sys.excepthook = global_exception_hook

    app = QApplication(sys.argv)

    # 创建并显示启动画面
    splash = show_splash_screen(app)
    app.processEvents()

    # 设置全局字体
    font = QFont()
    font.setFamily("Microsoft YaHei" if sys.platform == 'win32' else "Arial")
    font.setPointSize(11)
    app.setFont(font)

    # 显示欢迎屏幕
    welcome = WelcomeScreen()
    welcome.show()

    # 关闭启动画面
    splash.finish(welcome)

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()